<template>
	<div class="w-100 user-page">
		<!-- 顶部栏 -->
		<div class="w-100 header row-ac-sb">
			<div class="row-ac">
				<div class="font-s-18 font-w" style="margin-left: 1rem;">客服管理后台</div>
				<div class="row-ac font-s-15" style="margin-left: 5rem;">
					<NuxtLink class="flex-1 row-ac-jc py-2 row-ac" to="/admin"
						:class="{ active: currentRoute === '/admin' }">
						<div class="nav-link row-ac">
							<div class="font-s-16">girls</div>
						</div>
					</NuxtLink>
					<NuxtLink class="flex-1 row-ac-jc py-2 row-ac" to="/admin/crad"
						:class="{ active: currentRoute === '/admin/crad' }">
						<div class="nav-link row-ac">
							<div class="font-s-16 ml-10">crad</div>
						</div>
					</NuxtLink>
					<NuxtLink class="flex-1 row-ac-jc py-2 row-ac" to="/admin/user"
						:class="{ active: currentRoute === '/admin/user' }">
						<div class="nav-link row-ac">
							<div class="font-s-16 ml-10">user</div>
						</div>
					</NuxtLink>
					<NuxtLink class="flex-1 row-ac-jc py-2 row-ac" to="/admin/chat"
						:class="{ active: currentRoute === '/admin/chat' }">
						<div class="nav-link row-ac">
							<div class="font-s-16 ml-10">chat</div>
						</div>
					</NuxtLink>
				</div>
			</div>
			<div class="row-ac">
				<div class="" style="margin-right: 1.8rem;position: relative;">
					<i class="iconfont icon-youxiang" style="font-size: 30px;"></i>
					<div class="msg-number row-ac-jc">{{ totalUnreadCount }}</div>
				</div>
				<div class="row-ac" style="padding:0 1.5rem;">
					<img :src="meInfo.avatar" class="left-avatar" />
					<div class="font-s-16">{{ meInfo.nickname }}</div>
				</div>
				<div class="cursor-pointer" style="margin-right: 1rem;color: red;" @click="handleLogout">Logout</div>
			</div>
		</div>

		<!-- 主体 -->
		<div class="w-100 d-f">
			<!-- 左侧栏 -->
			<div class="left-bar" :style="'height:' + (documentHeight - 60) + 'px;'">
				<div class="px-10" v-if="currentRoute === '/admin/chat'">
					<div class="msg-item row-ac cursor-pointer" v-for="(item, index) in unreadList" :key="index"
						@click="takeSession(item.session_id)">
						<div class="img-box row-ac-jc">
							<i class="iconfont icon-morentouxiang" style="color: #dddddd;font-size: 24px;"></i>
						</div>
						<div class="font-s-16" style="margin-left: 0.5rem;">{{ item.initiate_user_id ? '':'游客' }}</div>
						<div class="msg-item-number row-ac-jc" v-if="item.total_unread > 0">{{ item.total_unread }}
						</div>
					</div>
				</div>
				<div class="px-10" v-if="currentRoute === '/admin/crad'">
					<div class="msg-item row-ac cursor-pointer">
						<!-- <div class="img-box row-ac-jc">
							<i class="iconfont icon-morentouxiang" style="color: #dddddd;font-size: 24px;"></i>
						</div>
						<div class="font-s-16" style="margin-left: 0.5rem;">{{ item.initiate_user_id ? '':'游客' }}</div>
						<div class="msg-item-number row-ac-jc" v-if="item.total_unread > 0">{{ item.total_unread }}
						</div> -->
					</div>
				</div>
				<div class="px-10" v-if="currentRoute === '/admin/user'">
					<div class="msg-item row-ac cursor-pointer">
						<!-- <div class="img-box row-ac-jc">
							<i class="iconfont icon-morentouxiang" style="color: #dddddd;font-size: 24px;"></i>
						</div>
						<div class="font-s-16" style="margin-left: 0.5rem;">{{ item.initiate_user_id ? '':'游客' }}</div>
						<div class="msg-item-number row-ac-jc" v-if="item.total_unread > 0">{{ item.total_unread }}
						</div> -->
					</div>
				</div>
			</div>
			<!-- 右侧内容区 -->
			<div class="right-box" :style="'height:' + (documentHeight - 60) + 'px;'">
				<slot></slot>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		useToken
	} from '@/composables/useToken'

	import {
		useRoute,
		useRouter
	} from 'vue-router'

	const {
		get
	} = useFetchApi()


	const {
		getToken,
		setToken,
		clearToken
	} = useToken()

	const router = useRouter()
	const route = useRoute();
	const currentRoute = computed(() => route.path);
	const loginStatus = ref(false)
	const documentHeight = ref(0)
	const unreadList = ref([])
	const totalUnreadCount = ref(0)
	const ws = ref(null)
	const heartbeatInterval = ref(null)
	const reconnectTimeout = ref(null)
	const reconnectDelay = 3000 // 3秒重连
	const sessionId = ref('')
	const meInfo = ref({
		avatar: "http://api.flirtyzsex.com/static/2025-2-2/WechatIMG164.jpg",
		nick: ""
	})

	// 父组件监听事件
	const emit = defineEmits(['update:sessionId'])

	const updateHeight = () => {
		documentHeight.value = window.innerHeight
	}

	const connectUnreadWebSocket = (token) => {
		if (!token) return

		const wsUrl = `ws://api.flirtyzsex.com/api/ws/chat/unread?token=${token}`
		ws.value = new WebSocket(wsUrl)

		ws.value.onopen = () => {
			console.log('✅ 已连接到未读消息 WebSocket')
			ws.value.send('fetch') // 首次拉取
		}

		ws.value.onmessage = (event) => {
			try {
				if (event.data === 'pong') return
				if (event.data === 'ping') {
					ws.value.send('pong')
					return
				}

				const data = JSON.parse(event.data)
				if (Array.isArray(data)) {
					unreadList.value = data
					totalUnreadCount.value = data.reduce((sum, s) => sum + s.total_unread, 0)

					// // 默认选择第一个会话
					// if (!sessionId.value && unreadList.value.length > 0) {
					// 	sessionId.value = unreadList.value[0].session_id
					// 	emit('update:sessionId', sessionId.value) // 通知父组件
					// }

				}
			} catch (e) {
				console.error('⚠️ WS 数据解析失败:', e, event.data)
			}
		}

		ws.value.onclose = () => console.log('🔌 WebSocket 已关闭')
		ws.value.onerror = (err) => console.error('❌ WebSocket 连接出错:', err)
	}

	const takeSession = (id) => {
		sessionId.value = id
		emit('update:sessionId', sessionId.value) // 点击切换也通知父组件
	}

	onMounted(async () => {
		updateHeight()
		window.addEventListener('resize', updateHeight)
		const token = getToken()
		if (token) {
			await meInfoData()
			loginStatus.value = true
			connectUnreadWebSocket(token)
		} else {
			loginStatus.value = false
		}
	})

	const meInfoData = async () => {
		try {
			const res = await get('/api/me_info');
			console.log(res);
			if (res.code == 200) {
				meInfo.value = res.data
				console.log(meInfo.value);
			}
		} catch (error) {
			console.error('Failed to fetch data:', error);
		}
	}

	onUnmounted(() => {
		window.removeEventListener('resize', updateHeight)
		if (ws.value) ws.value.close()
		if (heartbeatInterval.value) clearInterval(heartbeatInterval.value)
		if (reconnectTimeout.value) clearTimeout(reconnectTimeout.value)
	})

	const handleLogout = () => {
		clearToken()
		loginStatus.value = false
		console.log('已退出登录')
		router.push('/admin/login');
	}
</script>

<style scoped>
	.user-page {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif !important;
	}

	.w-100 {
		width: 100%;
	}

	.d-f {
		display: flex;
	}

	.header {
		height: 60px;
		background-color: #f5f5f5;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.left-bar {
		width: 280px;
		background-color: #f5f5f5;
		box-sizing: border-box;
		overflow-y: auto;
		overflow-x: hidden;
		padding: 8px;
	}

	.right-box {
		flex: 1;
		background-color: #fff;
	}

	.status-box {
		padding: 8px;
	}

	.status-box button {
		margin: 4px 0;
		padding: 6px 10px;
		background: #fff;
		color: #333;
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	.status-box button:hover {
		background: #ddd;
	}

	.right-content {
		padding: 10px;
	}

	.msg-number {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background-color: red;
		color: #fff;
		font-size: 13px;
		position: absolute;
		top: -2px;
		right: -12px;
	}

	.msg-item {
		padding: 10px 0;
		border-bottom: 1px solid #ededed;
		position: relative
	}

	.msg-item-number {
		width: 20px;
		height: 20px;
		border-radius: 50%;
		background-color: red;
		color: #fff;
		font-size: 13px;
		position: absolute;
		top: -2px;
		left: -2px;
	}

	.img-box {
		width: 35px;
		height: 35px;
		border-radius: 50%;
		background-color: #c4c4c4;
	}

	.left-avatar {
		width: 35px;
		height: 35px;
		border-radius: 50%;
	}

	.nav-link:hover {
		color: #ff814a;
	}

	.active {
		color: #ff814a;
	}
</style>